package com.cn.wolf.nio.groupchat;

import com.cn.wolf.common.Constants;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author huangy 客户端
 * @since 2022/11/27 4:06 下午
 */
public class GroupChatClient {

    //选择器
    private Selector selector;

    //连接通道
    private SocketChannel sc;

    /**
     * 账号
     */
    private String username;

    public GroupChatClient() {
        try {
            selector = Selector.open();
            //连接
            sc = SocketChannel.open(new InetSocketAddress(Constants.HOST, Constants.PORT));
            sc.configureBlocking(false);
            //进行通道注册
            sc.register(selector, SelectionKey.OP_READ);
            username = sc.getLocalAddress().toString().substring(1);
            System.out.println(username + " 上线了 ");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
     * @description 发送消息给服务器
     * @author huangy
     * @since 2023/1/16 18:29
     **/
    private void sendInfo(String info) {
        info = username + " 说: " + info;
        try {
            sc.write(ByteBuffer.wrap(info.getBytes(StandardCharsets.UTF_8)));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    private void readInfo() {
        try {
            int readCount = selector.select();
            if (readCount > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        //读取信息
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        channel.read(byteBuffer);
                        String msg = new String(byteBuffer.array());
                        System.out.println("收到服务器消息: " + msg.trim());
                    }
                    iterator.remove();
                }
            } else {
                System.out.println("没有可用的通道");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        GroupChatClient chatClient = new GroupChatClient();
        //开启一个线程 每隔3秒读取从服务端发送的消息
        new Thread(() -> {
            while (true) {
                chatClient.readInfo();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
        //向服务器发送信息
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String msg = scanner.next();
            chatClient.sendInfo(msg);
        }
    }

}
